package com.example.gateway.filter;

import com.example.common.constant.SecurityConstants;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.Payload;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order(0)
@Slf4j
public class SecurityGlobalFilter implements GlobalFilter {
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 不是正确的JWT不做解析处理
        String token = request.getHeaders().getFirst(SecurityConstants.AUTHORIZATION);
        if (StringUtils.isBlank(token) || !StringUtils.startsWithIgnoreCase(token, SecurityConstants.JWT_PREFIX)){
            log.info("token不是以规定模式传入，不进行token的解析");
            return chain.filter(exchange);
        }

        token = StringUtils.replaceIgnoreCase(token, SecurityConstants.JWT_PREFIX, "");
        Payload payload = JWSObject.parse(token).getPayload();

        log.info("payload的值：" + payload.toString());
        request.mutate().header(SecurityConstants.HEADER_USER_INFO, payload.toString());

        exchange = exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }
}
